<template>
  <div class="ai-message-list" ref="messageContainer">
    <!-- 欢迎消息 -->
    <div v-if="messages.length === 0" class="welcome-section">
      <div class="welcome-icon">{{ welcomeIcon || '🤖' }}</div>
      <h3>{{ welcomeTitle || '开始对话' }}</h3>
      <p>{{ welcomeMessage || '我是您的AI助手，有什么可以帮助您的吗？' }}</p>
      
      <!-- 快速开始按钮 -->
      <div class="quick-start" v-if="quickStart && quickStart.length > 0">
        <h4>快速开始：</h4>
        <div class="quick-start-grid">
          <div
            v-for="item in quickStart"
            :key="item.text"
            class="quick-start-item"
            @click="$emit('quickStart', item)"
          >
            <div class="quick-start-icon">{{ item.icon }}</div>
            <span>{{ item.text }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 消息列表 -->
    <div class="messages-container">
      <div
        v-for="(message, index) in messages"
        :key="message.id || index"
        :class="['message-item', message.type, { 'is-typing': message.isTyping }]"
      >
        <!-- 用户消息 -->
        <div v-if="message.type === 'user'" class="user-message">
          <div class="message-content">
            <div class="message-text">{{ message.content }}</div>
            <div v-if="message.image" class="message-image">
              <img :src="message.image" alt="用户上传的图片" @click="previewImage(message.image)" />
            </div>
          </div>
          <div class="message-avatar">
            <van-icon name="user-o" />
          </div>
        </div>

        <!-- AI消息 -->
        <div v-else class="ai-message">
          <div class="message-avatar">
            <div class="ai-avatar">{{ aiIcon || '🤖' }}</div>
          </div>
          <div class="message-content">
            <!-- 文本内容 -->
            <div v-if="message.content" class="message-text">
              <div v-if="message.isTyping" class="typing-text">
                {{ message.content }}
                <span class="typing-cursor">|</span>
              </div>
              <div v-else v-html="formatMessage(message.content)"></div>
            </div>

            <!-- 图片内容 -->
            <div v-if="message.images && message.images.length > 0" class="message-images">
              <div
                v-for="(image, imgIndex) in message.images"
                :key="imgIndex"
                class="image-item"
              >
                <img
                  :src="image.url || image"
                  :alt="image.alt || '生成的图片'"
                  @click="previewImage(image.url || image, message.images.map(img => img.url || img))"
                  @error="handleImageError(image, message, imgIndex)"
                  @load="handleImageLoad(image, message)"
                />
                <div class="image-actions" v-if="image.actions !== false">
                  <van-button size="mini" type="primary" @click="previewImage(image.url || image)">
                    预览
                  </van-button>
                  <van-button size="mini" @click="downloadImage(image.url || image)">
                    下载
                  </van-button>
                </div>
              </div>
            </div>

            <!-- 加载状态 -->
            <div v-if="message.isLoading" class="loading-indicator">
              <van-loading size="16" />
              <span>{{ message.loadingText || 'AI正在思考中...' }}</span>
            </div>

            <!-- 错误状态 -->
            <div v-if="message.error" class="error-indicator">
              <van-icon name="warning-o" />
              <span>{{ message.error }}</span>
              <van-button size="mini" type="primary" @click="$emit('retry', message)">
                重试
              </van-button>
            </div>

            <!-- 消息操作 -->
            <div class="message-actions" v-if="!message.isLoading && !message.error">
              <van-button
                size="mini"
                icon="thumb-circle-o"
                @click="$emit('like', message)"
                :class="{ active: message.liked }"
              />
              <van-button
                size="mini"
                icon="thumb-circle-o"
                @click="$emit('dislike', message)"
                :class="{ active: message.disliked, dislike: true }"
              />
              <van-button
                size="mini"
                icon="share-o"
                @click="$emit('share', message)"
              />
              <van-button
                v-if="message.content"
                size="mini"
                icon="copy"
                @click="copyMessage(message.content)"
              />
            </div>
          </div>
        </div>

        <!-- 消息时间 -->
        <div class="message-time">
          {{ formatTime(message.timestamp) }}
        </div>
      </div>
    </div>

    <!-- 正在输入指示器 -->
    <div v-if="isTyping" class="typing-indicator">
      <div class="typing-avatar">{{ aiIcon || '🤖' }}</div>
      <div class="typing-content">
        <div class="typing-dots">
          <span></span>
          <span></span>
          <span></span>
        </div>
        <span class="typing-text">{{ typingText || 'AI正在输入...' }}</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick, watch } from 'vue'
import { showToast } from 'vant'

// Props定义
interface Message {
  id?: string | number
  type: 'user' | 'ai'
  content?: string
  image?: string
  images?: Array<{ url: string; alt?: string; actions?: boolean } | string>
  timestamp: number
  isLoading?: boolean
  isTyping?: boolean
  error?: string
  loadingText?: string
  liked?: boolean
  disliked?: boolean
}

interface QuickStartItem {
  text: string
  icon: string
  data?: any
}

interface Props {
  messages: Message[]
  isTyping?: boolean
  typingText?: string
  welcomeIcon?: string
  welcomeTitle?: string
  welcomeMessage?: string
  aiIcon?: string
  quickStart?: QuickStartItem[]
  autoScroll?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  isTyping: false,
  autoScroll: true
})

// Emits定义
const emit = defineEmits<{
  quickStart: [item: QuickStartItem]
  like: [message: Message]
  dislike: [message: Message]
  share: [message: Message]
  retry: [message: Message]
  previewImage: [url: string, urls?: string[]]
}>()

// 响应式数据
const messageContainer = ref<HTMLElement>()

// 方法
const scrollToBottom = () => {
  if (!props.autoScroll || !messageContainer.value) return
  
  nextTick(() => {
    messageContainer.value!.scrollTop = messageContainer.value!.scrollHeight
  })
}

const formatTime = (timestamp: number) => {
  return new Date(timestamp).toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

const formatMessage = (content: string) => {
  // 简单的markdown格式化
  return content
    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
    .replace(/\*(.*?)\*/g, '<em>$1</em>')
    .replace(/`(.*?)`/g, '<code>$1</code>')
    .replace(/\n/g, '<br>')
}

const copyMessage = async (content: string) => {
  try {
    await navigator.clipboard.writeText(content)
    showToast('已复制到剪贴板')
  } catch (error) {
    console.error('复制失败:', error)
    showToast('复制失败')
  }
}

const previewImage = (url: string, urls?: string[]) => {
  emit('previewImage', url, urls)
}

const downloadImage = (url: string) => {
  const link = document.createElement('a')
  link.href = url
  link.download = `ai-image-${Date.now()}.png`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  showToast('开始下载图片')
}

const handleImageError = (image: any, message: Message, index: number) => {
  console.error('图片加载失败:', image)
  showToast('图片加载失败')
}

const handleImageLoad = (image: any, message: Message) => {
  scrollToBottom()
}

// 监听消息变化，自动滚动到底部
watch(
  () => props.messages.length,
  () => {
    scrollToBottom()
  }
)

watch(
  () => props.isTyping,
  () => {
    scrollToBottom()
  }
)

// 暴露方法
defineExpose({
  scrollToBottom
})
</script>

<style scoped>
.ai-message-list {
  height: 100%;
  overflow-y: auto;
  padding: 16px;
  scroll-behavior: smooth;
}

.welcome-section {
  text-align: center;
  padding: 40px 20px;
  color: #64748b;
}

.welcome-icon {
  font-size: 64px;
  margin-bottom: 16px;
}

.welcome-section h3 {
  font-size: 20px;
  font-weight: 600;
  color: #1e293b;
  margin: 0 0 8px 0;
}

.welcome-section p {
  font-size: 14px;
  margin: 0 0 24px 0;
  line-height: 1.5;
}

.quick-start h4 {
  font-size: 16px;
  font-weight: 600;
  color: #374151;
  margin: 0 0 12px 0;
}

.quick-start-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  gap: 12px;
  max-width: 400px;
  margin: 0 auto;
}

.quick-start-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  background: #f8fafc;
  border: 1px solid #e2e8f0;
  border-radius: 12px;
  padding: 16px 12px;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 13px;
}

.quick-start-item:hover {
  background: #e2e8f0;
  border-color: #3b82f6;
  color: #3b82f6;
}

.quick-start-icon {
  font-size: 24px;
}

.messages-container {
  max-width: 100%;
}

.message-item {
  margin-bottom: 24px;
}

.user-message {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.ai-message {
  display: flex;
  gap: 12px;
}

.message-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: #e2e8f0;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  color: #64748b;
}

.ai-avatar {
  font-size: 18px;
}

.message-content {
  max-width: 70%;
  min-width: 120px;
}

.user-message .message-content {
  background: #3b82f6;
  color: white;
  border-radius: 18px 18px 4px 18px;
  padding: 12px 16px;
}

.ai-message .message-content {
  background: white;
  border: 1px solid #e2e8f0;
  border-radius: 18px 18px 18px 4px;
  padding: 12px 16px;
}

.message-text {
  line-height: 1.5;
  word-wrap: break-word;
}

.typing-text {
  position: relative;
}

.typing-cursor {
  animation: blink 1s infinite;
}

@keyframes blink {
  0%, 50% { opacity: 1; }
  51%, 100% { opacity: 0; }
}

.message-image img,
.message-images img {
  max-width: 200px;
  max-height: 200px;
  border-radius: 8px;
  cursor: pointer;
  transition: transform 0.2s ease;
}

.message-image img:hover,
.message-images img:hover {
  transform: scale(1.02);
}

.message-images {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 12px;
  margin-top: 8px;
}

.image-item {
  position: relative;
}

.image-actions {
  display: flex;
  gap: 4px;
  margin-top: 8px;
}

.loading-indicator,
.error-indicator {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #64748b;
  font-size: 14px;
}

.error-indicator {
  color: #ef4444;
}

.message-actions {
  display: flex;
  gap: 4px;
  margin-top: 8px;
  opacity: 0.6;
  transition: opacity 0.2s ease;
}

.message-item:hover .message-actions {
  opacity: 1;
}

.message-actions .van-button.active {
  color: #3b82f6;
}

.message-actions .van-button.dislike.active {
  color: #ef4444;
}

.message-time {
  font-size: 12px;
  color: #94a3b8;
  text-align: center;
  margin-top: 4px;
}

.typing-indicator {
  display: flex;
  gap: 12px;
  align-items: center;
  margin-bottom: 16px;
}

.typing-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: #e2e8f0;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  color: #64748b;
}

.typing-content {
  display: flex;
  align-items: center;
  gap: 8px;
  background: white;
  border: 1px solid #e2e8f0;
  border-radius: 18px 18px 18px 4px;
  padding: 12px 16px;
}

.typing-dots {
  display: flex;
  gap: 4px;
}

.typing-dots span {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: #94a3b8;
  animation: typing 1.4s infinite ease-in-out;
}

.typing-dots span:nth-child(1) { animation-delay: -0.32s; }
.typing-dots span:nth-child(2) { animation-delay: -0.16s; }

@keyframes typing {
  0%, 80%, 100% {
    transform: scale(0.8);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

.typing-text {
  font-size: 14px;
  color: #64748b;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .message-content {
    max-width: 85%;
  }
  
  .quick-start-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style>
